'''

Copyright 2010 Manuel Reinelt

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Created on 12.04.2010

@author: Manuel Reinelt
contact: mrdevlab@googlemail.com

'''
import os
import platform
import ctypes
import sys

def check_disk_space(filesize, multipl, location, verbose):
    '''
    check if destination has enough disk space left
    and output location exists
    os.statvfs is not available on windows systems
    takes a multplier i. e. for uncompression where
    double size of free space may be needed
    returns free disk space and stops if it is not
    sufficient 
    exits on free size 0, returns fressize if > 0
    '''

    location = os.path.dirname(location)
              
    #check if output location exists    
    
    if verbose:
        print "checking if " + location + " exists"
                  
    if not os.path.isdir(location):
        print "ERROR: location: " + location + " not found, exiting"
        sys.exit(-1)
    elif platform.system() == 'Windows':
        
        if verbose:
            print "detected Windows, checking free space on " + location
        free_bytes = ctypes.c_ulonglong(0)
        ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(location), None, None, ctypes.pointer(free_bytes))
        freesize = free_bytes.value
    else:
        if verbose:
            print "detected X-OS, checking free space on " + location  
        freesize = os.statvfs(location).f_bfree
        return freesize
            
    if freesize - filesize * multipl <= 0:
        print "ERROR: insufficient disk space, exiting"
        sys.exit(-1) 